from flask import g
from flask_restful import Resource, reqparse, abort, fields, marshal

from App.apis.api_constant import HTTP_CREATE_OK
from App.apis.cinema_admin.utils import login_required
from App.models.cinema_admin.cinema_address_model import CinemaAddress
from App.models.cinema_admin.cinema_hall_model import Hall
from App.models.cinema_admin.cinema_hall_movie_model import HallMovie
from App.models.cinema_admin.cinema_movie_model import CinemaMovie

parse = reqparse.RequestParser()
parse.add_argument("movie_id" , required = True , type = int, help = "请选择电影")
parse.add_argument("hall_id" , required = True ,type = int ,  help = "请选择大厅")
parse.add_argument("h_time" , required = True , help = "请选择排挡时间")

hall_movie_fields = {
    "movie_id":fields.Integer(attribute="h_movie_id"),
    "hall_id":fields.Integer(attribute="hall_id"),
    "time":fields.DateTime(attribute="h_time")
}

class CinemaMovieHallResource(Resource):

    def get(self):
        return 'ok'

    @login_required
    def post(self):
        args = parse.parse_args()
        movie_id = args.get("movie_id")
        hall_id = args.get("hall_id")
        h_time = args.get("h_time")

        # 验证movie_id是否是已经购买过的
        # hall_id是不是我们用户的
        # h_time 不低于当前时间(过期票不显示)
        # 同时间的同一个放映厅是否有不同的电影，时间至少要错开first_duration

        # 验证movie_id是否是已经购买过的
        cinema_movies = CinemaMovie.query.filter(CinemaMovie.c_cinema_id == g.user_id).all()
        movies_buyed = [movie.c_movie_id for movie in cinema_movies]
        print('买了的电影id有：',movies_buyed,'=======')
        if not movie_id in movies_buyed:
            abort(400 , msg = "电影都没授权还想看？")

        # 验证hall_id是不是我们用户的
        cinema_addresses = CinemaAddress.query.filter(CinemaAddress.C_user_id == g.user_id).all()
        address_ids = [cinema_address.id for cinema_address in cinema_addresses]
        print('user_id有哪些地址:',address_ids,'======')
        address_hall_nums = []
        for address_id in address_ids:
            halls = Hall.query.filter(Hall.h_address_id == address_id).all()
            hall_nums = [hall.id for hall in halls]
            address_hall_nums.append(hall_nums)
        print('当前用户下每个地址所拥有的放映厅:', address_hall_nums, '======')
        each_hall_nums = []
        for i in address_hall_nums:
            for j in i:
                each_hall_nums.append(j)
        print(each_hall_nums , '===所有的放映厅====')
        if not hall_id in each_hall_nums:
            abort(400, msg="没有编排这个放映厅")


        hall_movie = HallMovie(h_movie_id = movie_id , h_hall_id = hall_id , h_time = h_time)
        if not hall_movie.save():
            abort(400 , msg = "拍档失败")

        data = {
            "status":HTTP_CREATE_OK,
            "msg":"ok",
            "data":marshal(hall_movie , hall_movie_fields)
        }
        return data


